package com.example.community.controller;

import com.example.community.model.dto.AccessTokenDTO;
import com.example.community.provider.GithubProvider;
import com.example.community.provider.dto.GithubUserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class AuthorizeController {

    @Autowired
    private GithubProvider githubProvider;

    @GetMapping("/callback")
    public String callback(@RequestParam String code, @RequestParam String state) {


        // 使用lombok的@Builder，简化对象创建
        AccessTokenDTO accessTokenDTO = AccessTokenDTO.builder()
                .client_id("Ov23liCkwPr2KMjkmfSY")
                .client_secret("8d075e2e006b29a59efa02a50b930cc6602e5da1")
                .code(code)
                .redirect_uri("http://localhost:8080/callback")
                .state(state)
                .build();


        /* 2.获得callback回调地址中的code和步骤一中提供的state，加上所需参数
        调用access_token接口获得access_token */
        String accessToken = githubProvider.getAccessToken(accessTokenDTO);

        // 3.通过access_token调用user接口获得用户信息
        GithubUserDTO user = githubProvider.getUser(accessToken);

        System.out.println(user);
        return "index";
    }
}
